from django.contrib.auth.hashers import check_password

from utils import restful
from .models import User


def register(request):
    username = request.POST.get('username')
    data = request.POST.dict()
    if User.objects.filter(username = username):
        return restful.params_error(message = '用户名已存在')
    else:
        user = User(**data)
        user.save()
        result = {
            'id': user.id,
            'username': user.username,
        }
        return restful.ok(data = result)


def login(request):
    username = request.POST.get('username')#获取前端传来的username
    password = request.POST.get('password')
    try:
        user = User.objects.get(username = username)#获取的前端用户名是否存在于用户表中
    except:
        return restful.params_error(message = '用户名不存在')#返回错误提示
    if user.password == password:
        result = {
            'id': user.id,
            'username': user.username,
        }
        return restful.ok(data = result) #响应，返回前端

    return restful.params_error(message = '用户名或密码错误')
